import ajaxAsync from 'vue-xiaobu-utils'
import BankCard from '../model/BankCard'
import * as status from '../constants/CardState'

// 公交云卡卡实例
const BUS_CARD = 'jhx_buscard'

/**
 *获取公交卡绑定状态
 *
 * @returns state 卡的开通状态
 */
async function checkBusCardState() {
  let result = await ajaxAsync('/vcard/info/list', {})
  let state
  if (result.COUNT === 0) state = false
  else {
    let cardList = result.LIST
    let item = cardList.find(item => item.CARD_INSTANCE_ID === BUS_CARD)
    state = item.STATE
  }
  return state
}

/**
 *获取钱包余额
 *
 * @returns
 */
async function getWalletBalance() {
  try {
    let rs = await ajaxAsync('/wallet/balance/get', {}, 1)
    return [rs.STATUS, rs.BALANCE]
  } catch (err) {
    let errCode = err.error.data.RSPCD
    if (errCode === 'CARD100116') {
      // 未开通的时候，以错误码的形势返回
      return [status.CARD_STATE_NOT_OPEND, '0.00']
    }
  }
}

/**
 *获取绑定的银行卡列表
 *
 * @returns
 */
async function getBankCardList() {
  let rs = await ajaxAsync('/bindcard/list', {})
  let bankCardList = []
  if (rs.COUNT > 0) {
    rs.LIST.map(item => {
      bankCardList.push(
        new BankCard(item.BIND_CARD_ID, item.CARD_NAME_DESC, item.BANK_CARD_NO)
      )
    })
  }
  return bankCardList
}

/**
 *解绑银行卡
 *
 * @param {String} bindCardID 绑卡记录编号
 * @returns
 */
async function unbindBankCard(bindCardID) {
  let rs = await ajaxAsync('/bindcard/unbind', { BIND_CARD_ID: bindCardID })
  return rs.BIND_STATUS === 3
}

export { getBankCardList, checkBusCardState, getWalletBalance, unbindBankCard }
